<?php

namespace app\common\middleware;

use app\common\model\UserMain;
use think\facade\Cache;
use think\facade\Cookie;
use think\facade\Session;
use think\facade\View;

class Common
{
    public function handle($request, \Closure $next)
    {
        global $_G;
        $login = Session::get('login');
        if (empty($login)) {
            $login = json_decode(authcode(Cookie::get('login')), true);
        }
        $_G = [
            'uid'     => empty($login['uid']) ? 0 : intval($login['uid']),
            'user'    => [],
            'setting' => Cache::get('common_setting') ?: (new \app\common\model\CommonSetting)->getAll(),
        ];
        if ($_G['uid'] > 0) {
            $_G['user'] = UserMain::where('uid', '=', $_G['uid'])->find();
            if (empty($_G['user']) || $login['password'] !== md5($_G['user']['password']) || $_G['user']['status'] < 0 || (empty($_G['setting']['allow_same_login']) && $_G['user']->getData('last_time') != $login['last_time'])) {
                (new UserMain)->logout();
            }
            if (!empty($_G['user']) && empty(Session::get('login'))) {
                $_G['user']->login();
            }
            unset($_G['user']['password']);
            unset($_G['user']['password_see']);
        }
        if (!empty($_G['user'])) {
            $_G['user']->update_access_time();
        }
        $spread_uid = (int) $request->param('f/d');
        if (
            $spread_uid &&
            !empty($_G['setting']['user_fission_time']) &&
            $_G['setting']['user_fission_time'] > 0 &&
            !empty($_G['setting']['user_fission']) &&
            $_G['setting']['user_fission_lv'] >= 0 &&
            empty(Cookie::get('spread_uid'))
        ) {
            $spread_user = $_G['uid'] != $spread_uid ? UserMain::where('uid', '=', $spread_uid)->find() : false;

            if (!empty($spread_user)) {
                Cookie::set('spread_uid', authcode($spread_user['uid'], 'ECODE'), $_G['setting']['user_fission_time'] * 3600);
            }
        }
        View::assign(['_G' => $_G]);
        return $next($request);
    }
}
